import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()
//   console.log("token:"+hasToken)

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       // determine whether the user has obtained his permission roles through getInfo
//       const hasRoles = store.getters.roles && store.getters.roles.length > 0
//       // 测试是否有权限
//       console.log("permission:" + store.state.user.roles)
//       if (hasRoles) {
//         next()
//       } else {
//         try {
//           // get user info
//           // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
//           const { roles } = await store.dispatch('user/getInfo')

//           console.log('查询后的权限:'+ roles)

//           // generate accessible routes map based on roles
//           const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

//           console.log("需要加载的路由："+accessRoutes)
//           // dynamically add accessible routes
//           router.addRoutes(accessRoutes)

//           // hack method to ensure that addRoutes is complete
//           // set the replace: true, so the navigation will not leave a history record
//           next({ ...to, replace: true })
//         } catch (error) {
//           console.log("测试是否有权限:" + store.getters.roles)
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           // 解决登录报错 Property "visible" must be accessed with "$data.visible" because
//           // Message.error(error || 'Has Error')
//           console.log('Has Error')
//           // Message.error('Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// 此处控制动态加载路由
router.beforeEach((to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  if (to.path == '/') {
    next()
    NProgress.done
  } else {    
    if (getToken()) {
      if (to.path == '/login') {
        next({ path: '/home' })
        NProgress.done
      } else {
        if (store.getters.roles.length === 0) {
          // 判断当前用户是否已拉取完user_info信息
          console.log("获取用户信息")
          store.dispatch('user/getInfo').then(res => {
            // 这里的res是getInfo中resolve的值，如果getInfo中最后resolve(data)，则res为接口返回的data（即resp.data），这时roles = res.roles
            // 拉取user_info 
            const roles = res.data.roles
            console.log("权限")
            // const roles = {
            //   "menus": [ "zyview","Resourceview","viewmessage"]
            // }
            console.log(roles);
            // 添加404，使得未加载的路由显示404
            roles.menus.push('404')
            store.dispatch('permission/generateRoutes', { roles }).then(() => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(store.getters.addRoutes)   // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          })
            // .catch(
            //   store.dispatch('user/FedLogOut').then(() => {
            //     console.log("请重新登录")
            //     next({path: '/login'})
            //     // next(`/login?redirect=${to.path}`)
            //   })
            // )
            .catch(() => {
              store.dispatch('user/FedLogOut').then(() => {
                Message.warning('登录信息已过期，请您重新登录！')
                next({ path: '/login' })
              })
            })
        } else {
          next()
        }
      }
    } else {
      /* has no token */
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next()
      } else {
        next('/login') // 否则全部重定向到登录页
        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
